package module

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "os"
    "path"
    "strconv"
    "strings"
    "yi-shou-backstage/config"
    "yi-shou-backstage/errmsg"
    "yi-shou-backstage/model"
    "yi-shou-backstage/module/result"
    "yi-shou-backstage/util"
)

func AuthorizationsControl(req *gin.Context) (int, string, interface{}) {
    // 解析参数
    var params model.User
    err := req.ShouldBindJSON(&params)
    if err != nil {
        util.LogEntry.Errorf("参数格式错误, error = %s, param = %s \n", err, params)
        return errmsg.PARAM_FORMAT_ERROR, errmsg.GetErrorByCode(errmsg.PARAM_FORMAT_ERROR), nil
    }

    // 校验参数
    user := model.QueryUserFirst(model.User{Mobile: params.Mobile})
    if user == nil {
        util.LogEntry.Errorf("该用户不存在, mobile = %s \n", params.Mobile)
       return errmsg.USER_NOT_EXIST, errmsg.GetErrorByCode(errmsg.USER_NOT_EXIST), nil
    }
    // 判断验证码是否正确
    if user.Code != params.Code {
        util.LogEntry.Errorf("验证码错误, code = %s \n", user.Code)
        return errmsg.CODE_ERROR, errmsg.GetErrorByCode(errmsg.CODE_ERROR), nil
    }

    // 签发token
    token, err := util.GenerateToken(user.ID)
    if err != nil {
        util.LogEntry.Errorf("签发Token失败，error = %s \n", err)
        return errmsg.GENERATE_TOKEN_ERROR, errmsg.GetErrorByCode(errmsg.GENERATE_TOKEN_ERROR), nil
    }
    refresh_token, _ := util.GenerateRefreshToken(user.ID)

    user.Token = token
    user.RefreshToken = refresh_token
    //resp.Photo = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fgss0.baidu.com%2F9fo3dSag_xI4khGko9WTAnF6hhy%2Fzhidao%2Fpic%2Fitem%2F94cad1c8a786c9175ddbf3f4cc3d70cf3ac75726.jpg&refer=http%3A%2F%2Fgss0.baidu.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1634141074&t=b40bc87d74fad15eab0ee31584542660"
    //resp.Photo = "https://ss3.baidu.com/9fo3dSag_xI4khGko9WTAnF6hhy/baike/pic/item/b7003af33a87e95027478f5613385343fbf2b4b3.jpg"
    return errmsg.SUCCESS, errmsg.GetErrorByCode(errmsg.SUCCESS), user
}

func RefreshTokenControl(req *gin.Context) (int, string, interface{}) {
    user_info := util.GetUserInfo(req)
    if user_info == nil {
        util.LogEntry.Errorf("token不存在或已过期 \n")
        return errmsg.TOKEN_IS_EXPIRED, errmsg.GetErrorByCode(errmsg.TOKEN_IS_EXPIRED), nil
    }
    user_id := user_info.UserID

    token, err := util.GenerateToken(user_id)
    if err != nil {
        util.LogEntry.Errorf("签发token失败，error = %s \n", err)
        return errmsg.GENERATE_TOKEN_ERROR, errmsg.GetErrorByCode(errmsg.GENERATE_TOKEN_ERROR), nil
    }

    data := model.User{Token: token}
    return errmsg.SUCCESS, errmsg.GetErrorByCode(errmsg.SUCCESS), data
}

func PatchUserPhotoControl(req *gin.Context) (int, string, interface{}) {
    user_info := util.GetUserInfo(req)
    if user_info == nil {
        util.LogEntry.Errorf("token不存在或已过期 \n")
        return errmsg.TOKEN_IS_EXPIRED, errmsg.GetErrorByCode(errmsg.TOKEN_IS_EXPIRED), nil
    }
    user_id := user_info.UserID

    user := model.GetUser(user_id)
    if user == nil {
        util.LogEntry.Errorf("该用户不存在, user_id = %s \n", user_id)
        return errmsg.USER_NOT_EXIST, errmsg.GetErrorByCode(errmsg.USER_NOT_EXIST), nil
    }

    file, err := req.FormFile("photo")
    if err != nil {
        util.LogEntry.Errorf("参数错误，error = %s \n", err)
        return errmsg.PARAM_ERROR, errmsg.GetErrorByCode(errmsg.PARAM_ERROR), nil
    }

    // 校验图片格式
    suffix := strings.ToLower(path.Ext(file.Filename))
    if suffix != ".jpg" && suffix != ".png" && suffix != ".jpeg" {
        util.LogEntry.Errorf("图片格式错误")
        return errmsg.PHOTO_FORMAT_ERROR, errmsg.GetErrorByCode(errmsg.PHOTO_FORMAT_ERROR), nil
    }

    pwd, _ := os.Getwd()  // 项目根路径
    filePath := fmt.Sprintf("%s/static/img/%s", pwd, file.Filename)
    err = req.SaveUploadedFile(file, filePath);
    if err != nil {
        util.LogEntry.Errorf("保存图片失败，error = %s \n", err)
        return errmsg.UPLOAD_FAILD, errmsg.GetErrorByCode(errmsg.UPLOAD_FAILD), nil
    }

    // 拼接图片路径
    serverAddress := fmt.Sprintf("%s:%d", config.Conf.Server.Host, config.Conf.Server.Port)
    photo := fmt.Sprintf("%s/static/img/%s", serverAddress, file.Filename)

    // todo 把图片路径插入数据库
    var obj model.User
    obj.Photo = photo
    data := model.UpdateUser(user_id, &obj)
    if data == nil {
        util.Logger.Errorf("更新用户失败，user_id = %s, obj = %s", user_id, obj)
        return errmsg.UPDATE_USER_ERROR, errmsg.GetErrorByCode(errmsg.UPDATE_USER_ERROR), nil
    }
    return errmsg.SUCCESS, errmsg.GetErrorByCode(errmsg.SUCCESS), data
}

// 编辑用户资料
func PatchUserProfileControl(req *gin.Context) (int, string, interface{}) {
    // 解析参数
    var params model.User
    err := req.ShouldBindJSON(&params)
    if err != nil {
        util.LogEntry.Errorf("参数错误, error = %s, param = %s \n", err, params)
        return errmsg.PARAM_ERROR, errmsg.GetErrorByCode(errmsg.PARAM_ERROR), nil
    }

    // 校验参数
    if ok, msg := util.Validator(&params); !ok {  // 校验失败
        util.LogEntry.Errorf("参数格式错误, error = %s, param = %s \n", err, params)
        return errmsg.PARAM_FORMAT_ERROR, msg, nil
    }

    // 更新用户信息
    user_info := util.GetUserInfo(req)
    if user_info == nil {
        util.LogEntry.Errorf("token不存在或已过期 \n")
        return errmsg.TOKEN_IS_EXPIRED, errmsg.GetErrorByCode(errmsg.TOKEN_IS_EXPIRED), nil
    }
    user_id := user_info.UserID

    data := model.UpdateUser(user_id, &params)
    if data == nil {
        util.Logger.Errorf("更新用户失败，user_id = %s, obj = %s", user_info.UserID, params)
        return errmsg.UPDATE_USER_ERROR, errmsg.GetErrorByCode(errmsg.UPDATE_USER_ERROR), nil
    }
    return errmsg.SUCCESS, errmsg.GetErrorByCode(errmsg.SUCCESS), data
}

// 获取用户个人资料
func GetUserProfileControl(req *gin.Context) (int, string, interface{}) {
    // 从请求上下文中获取用户信息
    user_info := util.GetUserInfo(req)
    if user_info == nil {
        util.LogEntry.Errorf("token不存在或已过期 \n")
        return errmsg.TOKEN_IS_EXPIRED, errmsg.GetErrorByCode(errmsg.TOKEN_IS_EXPIRED), nil
    }
    user_id := user_info.UserID

    // 查询用户信息
    data := model.GetUser(user_id)
    if data == nil {
        util.LogEntry.Errorf("该用户不存在, user_id = %d \n", user_id)
        return errmsg.USER_NOT_EXIST, errmsg.GetErrorByCode(errmsg.USER_NOT_EXIST) ,nil
    }
    return errmsg.SUCCESS, errmsg.GetErrorByCode(errmsg.SUCCESS), data
}

func GetFollowersControl(req *gin.Context) (int, string, interface{}) {
    // 获取参数
    page, err := strconv.Atoi(req.DefaultQuery("page", "-1"))
    per_page, err := strconv.Atoi(req.DefaultQuery("per_page", "-1"))
    if err != nil {
        util.LogEntry.Errorf("数据类型转换错误, error = %s \n", err)
        return errmsg.DATA_TYPE_CONV_ERROR, errmsg.GetErrorByCode(errmsg.DATA_TYPE_CONV_ERROR), nil
    }

    user_info := util.GetUserInfo(req)
    if user_info == nil {
        util.LogEntry.Errorf("token不存在或已过期 \n")
        return errmsg.TOKEN_IS_EXPIRED, errmsg.GetErrorByCode(errmsg.TOKEN_IS_EXPIRED), nil
    }

    // 查询粉丝
    total, rows := model.GetFollowers(user_info.UserID, page, per_page)
    if total == 0 {
        util.LogEntry.Errorf("查询粉丝失败 \n")
        return errmsg.ERROR, errmsg.GetErrorByCode(errmsg.ERROR), nil
    }

    var data result.FollowersResponse
    data.TotalCount = total
    data.Page = page
    data.PerPage = per_page
    data.Results = rows

    user := model.GetUser(user_info.UserID)
    if user == nil {
        util.LogEntry.Errorf("该用户不存在, user_id = %s \n", user_info.UserID)
        return errmsg.USER_NOT_EXIST, errmsg.GetErrorByCode(errmsg.USER_NOT_EXIST), nil
    }
    data.ID = user.ID
    data.Name = user.Name
    data.Photo = user.Photo
    return errmsg.SUCCESS, errmsg.GetErrorByCode(errmsg.SUCCESS), data
}